package com.rabbitmq.websocket;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.MultimapBuilder;
import com.rabbitmq.entity.MessageEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sun.plugin2.message.Message;

import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint(value = "/ws/asset/{userId}/{deptId}")
@Component
public class WebSocketServer {
    String userId;
    String deptId;

    @PostConstruct
    public void init() {
        System.out.println("websocket 加载");
    }
    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    private static final AtomicInteger OnlineCount = new AtomicInteger(0);
    private static ConcurrentHashMap<String, Session> userMap = new ConcurrentHashMap<>();
    private static HashMultimap<String, Session> deptMap = HashMultimap.create();


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId")String userId,@PathParam(value = "deptId")String deptId) {
        userMap.put(userId,session);
        deptMap.put(deptId,session);
        int cnt = OnlineCount.incrementAndGet(); // 在线数加1
        log.info("有连接加入，当前连接数为：{}", cnt);
        sendMessage(session, "连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam(value = "userId")String userId,@PathParam(value = "deptId")String deptId) {
        userMap.remove(userId);
        deptMap.remove(deptId,session);
        int cnt = OnlineCount.decrementAndGet();
        log.info("有连接关闭，当前连接数为：{}", cnt);
    }

    /**
     * 收到客户端消息后调用的方法
     * 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息：{}",message);
        sendMessage(session, "收到消息，消息内容："+message);

    }

    /**
     * 出现错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误：{}，Session ID： {}",error.getMessage(),session.getId());
        error.printStackTrace();
    }

    /**
     * 发送消息，实践表明，每次浏览器刷新，session会发生变化。
     * @param session
     * @param message
     */
    public static void sendMessage(Session session, String message) {
        try {
            session.getBasicRemote().sendText(String.format("%s (From Server，Session ID=%s)",message,session.getId()));
        } catch (IOException e) {
            log.error("发送消息出错：{}", e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 指定userId  Session发送消息
     * @param message
     * @throws IOException
     */
    public static void sendMessage(MessageEntity message,String userId) throws IOException {
        Session session = userMap.get(userId);
        if(session!=null){
            sendMessage(session, message.getMessage());
        }
        else{
            log.warn("没有找到你指定ID的会话：{}",userId);
        }
    }

}